<?php

namespace app\controller;

use lylib\captcha\LyVerify;
use rap\storage\File;
use rap\util\FileUtil;
use rap\util\http\Http;

/**
 * 扥扥东
 * 扥扥
 * @author: 藤之内
 */
class HomeController
{


    public function login($account,$password,$token)
    {
        $ver=LyVerify::checkToken($token);
        if(!$ver){
            exception('验证失败,请重新操作');
        }
        //如果用户验证后不希望用户再去修改账号密码,可以使用这段验证
        if($ver['params']['account']!==$account||$ver['params']['password']!==$password){
            exception('验证码和提交表单不符合,请重新验证');
        }
        //验证ip和session_id
        if($ver['session_id']!==request()->session()->sessionId()||$ver['ip']!== request()->ip()){
            exception('验证失败,请勿使用代理');
        }
        //验证时间
        if(time()-$ver['check_time']>60){
            exception('验证码已过期,请重新操作');
        }
        //模拟登录
        if($account!=='admin'||$password!='123456'){
            exception('用户登录信息错误,请使用 admin/123456 测试');
        }
        return success();
    }

    public function docToc()
    {
        $toc = FileUtil::readFile(RUNTIME . 'doc.json');
        if (!$toc) {
            $body = Http::get('https://www.yuque.com/yuque/ng1qth/about')->body;
            $index = strpos($body, 'JSON.parse(decodeURIComponent(') + strlen('JSON.parse(decodeURIComponent(') + 1;
            $end = strpos($body, "));", $index) - 1;
            $appData = substr($body, $index, $end - $index);
            $toc = json_decode(urldecode($appData), true)['book']['toc'];
            $toc = json_encode($toc);
        }
        return json_decode($toc, true);
    }



    public function files()
    {
        $items = [];
        $path = ROOT_PATH . 'portal/ly';
        FileUtil::eachAll($path, function ($file, $name) use (&$items) {
            if (is_dir($file)) {
                $children = $this->files($file);
                foreach ($children as $child) {
                    $items[] = $name . "/" . $child;
                }
            } else {
                if (substr($name, 0 - strlen('.html')) === '.html') {
                    $name = str_replace('.html', '', $name);
                    $items[] = $name;
                }
            }
        });
        return $items;
    }

    //这是直传演示
    public function upload(File  $file){
        //这里是演示上传代码
        $file_name='upload/'.date("Y-m-d", time()).'/'.time().'.'.$file->ext;
        FileUtil::copy($file->path_tmp,ROOT_PATH.$file_name);
        return [
            'url'=>'/'.$file_name
        ];
    }

    //



}